<?php

class ctrl_vsAccount extends L {

    /**
     * 描述 ：账号授权管理页面展示
     * 作者 ：Zoro.Zhu
    **/
    public function index(){
        $this->view->_pagingHtml = $this->paging();
        $this->view->headTitle = '账号授权管理';
        $this->view->type = model_com::getVsConfig('vsAccountType');
        $this->display('/html/vsAccount.html');
    }

    /**
     * 描述 : 获取分页
     * 作者 : Zoro.Zhu
     */
    public function &paging($params = array()){
        $sql = model_vsAccount::searchSql($params);
        $config = array( 
            '账号名称' => array(
                '_attr' => array(
                    'body' => '{`account`}',
                    'sort' => 'account'
                )
            ),
            '应用ID' => array(
                '_attr' => array(
                    'body' => '{`appKey`}',
                    'sort' => 'appKey'
                )
            ),
            '应用密钥' => '{`appSecret`}',
            '访问令牌' => '{`accessToken`}',
            '刷新令牌' => '{`refreshToken`}',
            '失效时间' => '{`invalidDate`}',
            '状态0开启1关闭' => array(
                '_attr' => array(
                    'body' => '{`state`}',
                    'sort' => 'state'
                )
            ),
            '账号类型' => array(
                '_attr' => array(
                    'body' => '{`type`}',
                    'sort' => 'type'
                )
            ),
            '添加时间' => array(
                '_attr' => array(
                    'body' => '{`addDate`}',
                    'sort' => 'addDate'
                )
            ),
            '授权' => '{`_getToken`}',
            '配送国家' => '{`_shipping`}',
            '操作'=> "<button class=\"btn btn-oper btn-danger\" type=\"button\" onclick=\"vsAccountObj.vsAccountUpInfo('{`account`}');\">
                <span class=\"fa fa-plus\"></span>修改
            </button>",
            '_attr' => array(
                "attr" => array (
                    "table" => 'id=vsAccountList class="table table-hover table-condensed table-striped table-scroll jsHoverDetails textC"',
                    "btr" => "align='center' class='of-paging_item_odd tr_{`account`}'",
                ),
                'data' => &$sql,
                'params' => &$params,
                'call' => array($this, 'asCall'),
                'method' => __METHOD__,
                'save' => 'auto',
                'empty' => '查无此数据'
            )
        );
        return $this->_com->paging($config);
    }

    /**
     * 描述 : 整理数据
     * 作者 : Zoro.Zhu
     */
    public function asCall(&$data){
        $typeAy = model_com::getVsConfig('vsAccountType');
        foreach($data['data'] as &$val){
            $val['_getToken'] = '<button class="btn btn-oper btn-warning" type="button" onclick="vsAccountObj.getToken(\'' . $val['account'] . '\', \'' . $val['type'] . '\');">
                <span class="fa fa-plus"></span>授权
            </button>';
            $val['state'] = empty($val['state']) ? '开启' : '关闭';
            $val['type'] = !empty($typeAy[$val['type']]) ? $typeAy[$val['type']] : $val['type'];
            $val['_shipping'] = $val['type'] == 'Wish' ? '<button class="btn btn-oper btn-info" type="button" onclick="vsAccountObj.getShipping(\'' . $val['account'] . '\');">
                <span class="fa fa-plus"></span>国家
            </button>' : '';
        }
    }

    /**
     * 描述 : 新增和修改的页面展示
     * 作者 : Zoro.Zhu
     */
    public function vsAccountUpInfo(){
        if(!empty($_REQUEST['account'])) {
            $vsAccount = model_vsAccount::getKeyInfo($_REQUEST['account']);
            if(!empty($vsAccount)){ 
                $this->view->account = $vsAccount[0]['account'];
                $this->view->appKey = $vsAccount[0]['appKey'];
                $this->view->appSecret = $vsAccount[0]['appSecret'];
                $this->view->accessToken = $vsAccount[0]['accessToken'];
                $this->view->refreshToken = $vsAccount[0]['refreshToken'];
                $this->view->invalidDate = $vsAccount[0]['invalidDate'];
                $this->view->state = $vsAccount[0]['state'];
                $this->view->type = $vsAccount[0]['type'];
                $this->view->addDate = $vsAccount[0]['addDate'];
                $this->view->data = $vsAccount[0]['data'];
            }
        }
        $this->view->typeAy = model_com::getVsConfig('vsAccountType');
        $this->display('/html/vsAccountUpInfo.html');
    }

    /**
     * 描述 ：新增或修改数据
     * 作者 ：Zoro.Zhu
    **/
    public function vsAccountUpd(){
        model_vsAccount::insertSql($_POST);
        return array('state' => 200, 'info' => '操作成功');
    }

    /**
     * 描述 ：按条件导出数据
     * 作者 ：Zoro.Zhu
    **/
    public function exportCsv(){
        $sql = model_vsAccount::searchSql(array('search' => $_GET));
        $data = L::sql($sql);
        of_base_com_csv::download('导出数据' . time());                     //导出数据的文件名
        of_base_com_csv::download(array('账号名称','应用ID','应用密钥','访问令牌','刷新令牌','失效时间','状态0开启1关闭','账号类型 1688，pdd','添加时间',));
        foreach ($data as $row){
            of_base_com_csv::download(array($row['account'],$row['appKey'],$row['appSecret'],$row['accessToken'],$row['refreshToken'],$row['invalidDate'],$row['state'],$row['type'],$row['addDate'],));
        }
    }

    /**
    * 描述 ：获取pdd的code，生成登录链接
    * 作者 ：Zoro.Zhu
    **/
    public function getCodeUrl(){
        if($_POST['type'] == 'pdd') {
            $url = model_api_pdd::codeUrl($_POST['account']);
        } elseif ($_POST['type'] == 'wishU'){
            $token = model_vsAccount::getAccountToken(['account' => $_POST['account']]);
            of_base_com_kv::set('accreditAccount' , json_encode($token), 3600);
            $url = "http://www.wishpost.cn/oauth/authorize?client_id=" . $token['appKey'];
        } elseif ($_POST['type'] == 'wish'){
            $token = model_vsAccount::getAccountToken(['account' => $_POST['account']]);
            of_base_com_kv::set('accreditAccount' , json_encode($token), 3600);
            $url = "https://merchant.wish.com/v3/oauth/authorize?client_id=" . $token['appKey'];
        } elseif ($_POST['type'] == 'ali'){
            $token = model_vsAccount::getAccountToken(['account' => $_POST['account']]);
            of_base_com_kv::set('accreditAccount' , json_encode($token), 3600);
            $url = "https://auth.1688.com/oauth/authorize?client_id={$token['appKey']}&site=1688&redirect_uri=https://6beams.com/serv/accredit1688.php&state=zoroGood";
        }
        return array('state' => 200, 'url' => $url, 'info' => '获取成功');
    }

    /**
     * 描述 : 获取该账号的配送国家
     * 作者 : Zoro.Zhu
     */
    public function getShipping(){
        $account = trim($_GET['account']);
        $token = model_vsAccount::getAccountToken(['account' => $account]);
        $shipping = serv_rapi_wish::getShipping($token);
        $country = model_com::getCountryCode();
        $data = [];
        foreach($shipping['data'] as $row){
            $data[$row['country_code']] = $row + $country[$row['country_code']];
        }
        $this->view->data = $data;
        $this->view->account = $account;
        $this->display('/html/vsAccountUpShipping.html');

    }

    /**
     * 描述 : 修改配送国家，调用wishAPI
     * 作者 : Zoro.Zhu
     */
    public function submitShipping(){
        if(empty($_POST['account']) || empty($_POST['country'])){
            return ['state' => 301, 'info' => '数据异常'];
        }
        $token = model_vsAccount::getAccountToken(['account' => $_POST['account']]);
        $country = [];
        foreach($_POST['country'] as $c => $e){
            $country[] = [
                'country_code' => $c,
                'enabled' => $e
            ];
        }
        $shipping = serv_rapi_wish::setShipping($token, $country);
        if($shipping['code'] === 0){
            return ['state' => 200, 'info' => $_POST['account'] . '设置成功'];
        } else {
            return ['state' => 302, 'info' => $_POST['account'] . $shipping['message']];
        }
    }
    /**
     * 描述 : 修改配送国家，调用wishAPI
     * 作者 : Zoro.Zhu
     */
    public function submitShippingAll(){
        set_time_limit(180);
        if(empty($_POST['country'])){
            return ['state' => 301, 'info' => '数据异常'];
        }
        $country = [];
        foreach($_POST['country'] as $c => $e){
            $country[] = [
                'country_code' => $c,
                'enabled' => $e
            ];
        }
        $account = explode(',', $_GET['account']);
        $sql = model_vsAccount::searchSql(['search' => ['type' => 'wish', 'accounts' => $account]]);
        $tokens = L::sql($sql);
        $info = "";
        foreach($tokens as $token){
            $shipping = serv_rapi_wish::setShipping($token, $country);
            if($shipping['code'] === 0){
                $info .= "{$token['account']}更新成功<br>";
            } else {
                $info .= "{$token['account']}{$shipping['message']}<br>";
            }
        }
        return ['state' => 200, 'info' => $info];
    }

    /**
     * 描述 : 账号列表
     * 作者 : Zoro.Zhu
    **/
    public function getShippingAccount(){
        $sql = model_vsAccount::searchSql(['search' => ['type' => 'wish']]);
        $tokens = L::sql($sql);
        $account = array_column($tokens, 'account');
        $this->view->account = $account;
        $this->display('/html/accountList.html');
    }

}
return true;